package com.lindroy.androidplayer.viewmodel

import androidx.lifecycle.MutableLiveData
import com.lindroy.androidplayer.base.viewmodel.BaseViewModel
import com.lindroy.androidplayer.extensions.request
import com.lindroy.androidplayer.extensions.yes
import com.lindroy.androidplayer.logic.model.ArticleResp
import com.lindroy.androidplayer.logic.model.KnowledgeNavResp
import com.lindroy.androidplayer.logic.model.KnowledgeResp
import com.lindroy.androidplayer.logic.network2.state.ResultState
import com.lindroy.androidplayer.logic.network2.apiService
import com.lindroy.androidplayer.logic.network2.statecallback.ListDataState

/**
 * @author Lin
 * @date 2021/4/28
 * @function 体系
 */
class KnowledgeViewModel : BaseViewModel() {

    private var pageNo = 0

    private var questionPage = 0

    var cid = 0

    val knowledgeState: MutableLiveData<ResultState<List<KnowledgeResp>>> = MutableLiveData()

    val navState:MutableLiveData<ResultState<List<KnowledgeNavResp>>> = MutableLiveData()

    val knowledgeDetailState: MutableLiveData<ListDataState<ArticleResp>> = MutableLiveData()

    val questionState: MutableLiveData<ListDataState<ArticleResp>> = MutableLiveData()

    /**
     * 获取体系目录
     */
    fun reqKnowledgeTree() {
        request({ apiService.getKnowledgeTree() }, knowledgeState)
    }

    /**
     * 获取导航目录
     */
    fun reqNavigationIndex(){
        request({ apiService.getNavigationData() }, navState)
    }

    /**
     * 获取某体系的文章
     */
    fun reqKnowledgeDetail(isRefresh: Boolean) {
        isRefresh.yes { pageNo = 0 }
        request({ apiService.getKnowledgeArticles(pageNo, cid) }, {
            knowledgeDetailState.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            pageNo++
        }, {
            knowledgeDetailState.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })
    }

    /**
     * 获取问答
     */
    fun reqQuestionList(isRefresh: Boolean){
        isRefresh.yes { questionPage = 0 }
        request({ apiService.getQuestionList(questionPage)},{
            questionState.value = ListDataState(
                success = true,
                isRefresh = isRefresh,
                isEmpty = it.isEmpty(),
                hasMore = it.hasMore(),
                isFirstEmpty = isRefresh && it.isEmpty(),
                listData = it.datas
            )
            questionPage++
        },{
            questionState.value = ListDataState(
                success = false,
                isRefresh = isRefresh,
                errMessage = it.errorMsg,
                listData = arrayListOf()
            )
        })
    }
}